package com.chuangan.releasetask.controller;

import com.chuangan.releasetask.Utils.ResultVOUtil;
import com.chuangan.releasetask.VO.ResultVO;
import com.chuangan.releasetask.converter.TaskForm2TaskMasterConverter;
import com.chuangan.releasetask.dto.StepDTO;
import com.chuangan.releasetask.dto.TaskDTO;
import com.chuangan.releasetask.enums.ResultEnum;
import com.chuangan.releasetask.enums.TaskStatusEnum;
import com.chuangan.releasetask.exception.ReleaseTaskException;
import com.chuangan.releasetask.form.TaskForm;
import com.chuangan.releasetask.mapper.TaskMapper;
import com.chuangan.releasetask.mapper.UserMapper;
import com.chuangan.releasetask.pojo.TaskMaster;
import com.chuangan.releasetask.pojo.TaskStep;
import com.chuangan.releasetask.pojo.User;
import com.chuangan.releasetask.quartz.QuartzExecute;
import com.chuangan.releasetask.service.TaskService;
import com.chuangan.releasetask.service.UserService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: zihua
 * @Date: 2020/8/11 16:59
 * @Version 1.0
 */
@CrossOrigin
@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private UserMapper userMapper;



    //测试单张图片上传
//    @PostMapping(value = "/testUpload2", headers = "content-type=multipart/form-data")
//    public ResultVO testUpload2(HttpServletRequest request, @RequestParam("file")MultipartFile [] files){
//        Map<String,Object> map = new HashMap<>();
//        for(MultipartFile multipartFile: files){
//            map.put("success", FileUtil.saveImageFile(request,multipartFile));
//        }
//        return ResultVOUtil.success(map);
//    }



    //测试多张图片上传
//    @RequestMapping("/uploadFile")
//    public ResultVO uploadFile(HttpServletRequest request) throws IOException {
//        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//        Map<String,Object> resultMap = new HashMap<>();
//        commonsMultipartResolver.setDefaultEncoding("utf-8");
//        if (commonsMultipartResolver.isMultipart(request)){
//            MultipartHttpServletRequest mulReq = (MultipartHttpServletRequest) request;
//            Map<String, MultipartFile> map = mulReq.getFileMap();
//            // key为前端的name属性，value为上传的对象（MultipartFile）
//            for (Map.Entry<String, MultipartFile> entry : map.entrySet()) {
//                // 自己的保存文件逻辑
//                //saveOrUpdateImageFile(feedback.getId(), entry.getKey(), entry.getValue());
//                resultMap.put("success",FileUtil.saveImageFile(request,entry.getValue()));
//            }
//        }
//        return ResultVOUtil.success(resultMap);
//
//    }




    @PostMapping(value = "/create", headers = "content-type=multipart/form-data")
    public ResultVO create(@Valid TaskForm taskForm, BindingResult bindingResult, MultipartRequest multipartRequest, HttpServletRequest req) throws Exception {
        if (bindingResult.hasErrors()) {
            log.error("【创建任务】参数不正确, taskForm={}", taskForm);
            throw new ReleaseTaskException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        TaskMaster taskMaster = TaskForm2TaskMasterConverter.convert(taskForm);
        User user = userMapper.findOneUser(taskMaster.getTaskPublisher());
        if(user.getUserBalance().compareTo(taskMaster.getTaskAmount())<0)
        {
            log.error("【创建任务】用户余额不足");
            throw new ReleaseTaskException(ResultEnum.BALANCE_NOT_ENOUGH);
        }
        if (CollectionUtils.isEmpty(taskMaster.getTaskStepList())) {
            log.error("【创建任务】任务步奏不能为空");
            throw new ReleaseTaskException(ResultEnum.STEP_EMPTY);
        }
        TaskMaster createResult = taskService.create(taskMaster,multipartRequest,req);
        user.setUserBalance(user.getUserBalance().subtract(taskMaster.getTaskAmount()));
        userMapper.creditCal(user.getUserBalance(), user.getUserAccount());
        QuartzExecute.auditDeadlineQuartz("com.chuangan.releasetask.job.AuditJob");
//        QuartzExecute.taskExpiredQuartz("com.chuangan.releasetask.job.TaskJob");
        Map<String, String> map = new HashMap<>();
        map.put("taskId", createResult.getTaskID());
        return ResultVOUtil.success(map);
    }

    @GetMapping("/acceptTask")
    public ResultVO acceptTask(String taskID,String userAccount) throws Exception {
        if (StringUtils.isEmpty(taskID) || StringUtils.isEmpty(userAccount)) {
            return ResultVOUtil.error(404,"任务ID或用户账号为空");
        }
        Map<String, String> map = new HashMap<>();
        List<StepDTO> stepDTOS =  taskMapper.selectAcceptedByAccount(taskID,userAccount);
        TaskMaster taskMaster = taskMapper.selectTaskById(taskID);
        if(stepDTOS.size()>0){
            return ResultVOUtil.error(402,"你已接受过此任务");
        }
        if(taskMaster.getEndTime().before(new Date())){
            return ResultVOUtil.error(403,"该任务已过期");
        }
        TaskDTO taskDTO = new TaskDTO();
        taskDTO.setTaskID(taskID);
        taskDTO.setUserAccount(userAccount);
        List<TaskStep> taskSteps =  taskMapper.selectTaskStepById(taskID);
        taskDTO.setTaskStepList(taskSteps);
        if(taskService.acceptTask(taskDTO,taskMaster)){
            map.put("message","接受任务成功");
            return ResultVOUtil.success(map);
        }
        else
        {
            return ResultVOUtil.error(404,"接受任务失败");
        }
    }

    @PostMapping("/commitTask")
    public ResultVO commitTask(@Valid TaskDTO taskDTO, BindingResult bindingResult, MultipartRequest multipartRequest, HttpServletRequest req) throws Exception {
        if (bindingResult.hasErrors()) {
            log.error("【提交任务】参数不正确, taskDTO={}", taskDTO);
            throw new ReleaseTaskException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        Gson gson = new Gson();
        Map<String, String> map = new HashMap<>();
        List<TaskStep> taskSteps;
        try {
            taskSteps = gson.fromJson(taskDTO.getItems(),
                    new TypeToken<List<TaskStep>>() {
                    }.getType());
        } catch (Exception e) {
            log.error("【对象转换】错误, string={}", taskDTO.getItems());
            throw new ReleaseTaskException(ResultEnum.PARAM_ERROR);
        }
        taskDTO.setTaskStepList(taskSteps);
        if(taskDTO.getEndTime().before(new Date())){
            map.put("message","该任务已过期");
            return ResultVOUtil.success(map);
        }
        if(taskService.commitTask(taskDTO,multipartRequest,req)){
            map.put("message","提交任务成功");
            return ResultVOUtil.success(map);
        }
        else
        {
            map.put("message","提交任务失败");
            return ResultVOUtil.success(map);
        }
    }


    @GetMapping("/acceptedTaskDetail")
    public ResultVO acceptedTaskDetail(String taskID, String userAccount)  {
        if (StringUtils.isEmpty(taskID) || StringUtils.isEmpty(userAccount)) {
            return ResultVOUtil.error(404,"任务ID或用户账号为空");
        }
        List<StepDTO> stepDTOS =  taskMapper.selectAcceptedByAccount(taskID,userAccount);
        return ResultVOUtil.success(stepDTOS);
    }

    @GetMapping("/taskListedByGroup")
    public ResultVO taskListedByGroup(int orderMode,String taskClass)  {
        // orderMode : 1.默认排序 2,最新发布 3.佣金最高
        List<TaskMaster> taskMasters = taskMapper.selectTaskListedByGroup(taskClass,orderMode);
        for(TaskMaster taskMaster: taskMasters){
            List<TaskStep> taskSteps = taskMapper.selectTaskStepById(taskMaster.getTaskID());
            taskMaster.setTaskStepList(taskSteps);
        }
        return ResultVOUtil.success(taskMasters);
    }

    @GetMapping("/taskListedByStatus")
    public ResultVO taskListedByStatus(int taskStatus,String userAccount)  {
        if(userAccount.equals("null"))
        {
            userAccount = null;
        }
        List<TaskMaster> taskMasters = taskMapper.selectTaskListedByStatus(taskStatus,userAccount);
        for(TaskMaster taskMaster: taskMasters){
            List<TaskStep> taskSteps = taskMapper.selectTaskStepById(taskMaster.getTaskID());
            taskMaster.setTaskStepList(taskSteps);
        }
        return ResultVOUtil.success(taskMasters);
    }


    @GetMapping("/searchTask")
    public ResultVO searchTask(String searchPara)  {
        List<TaskMaster> taskMasters = taskMapper.searchTaskListedByCondition(searchPara);
        for(TaskMaster taskMaster: taskMasters){
            List<TaskStep> taskSteps = taskMapper.selectTaskStepById(taskMaster.getTaskID());
            taskMaster.setTaskStepList(taskSteps);
        }
        return ResultVOUtil.success(taskMasters);
    }

    @GetMapping("/taskListedByWeight")
    public ResultVO taskListedByWeight()  {
        List<TaskMaster> taskMasters = taskMapper.selectTaskListedByWeight();
        for(TaskMaster taskMaster: taskMasters){
            List<TaskStep> taskSteps = taskMapper.selectTaskStepById(taskMaster.getTaskID());
            taskMaster.setTaskStepList(taskSteps);
        }
        return ResultVOUtil.success(taskMasters);
    }



    @GetMapping("/taskFlag")
    public ResultVO taskFlag(String taskID, String userAccount, int taskFlag)  {
        if (StringUtils.isEmpty(taskID) || StringUtils.isEmpty(userAccount)) {
            return ResultVOUtil.error(404,"任务ID或用户账号为空");
        }
        TaskMaster taskMaster = taskMapper.selectTaskById(taskID);
        List<TaskDTO> taskDTOList = taskMapper.selectTaskCountByStatus(taskID,4,1);
        if(taskFlag == 1){
            if(taskMaster.getTaskNumber()>taskDTOList.size()){
                taskMapper.taskFlag(taskID,userAccount,taskFlag);
                taskMapper.addFinishedTaskNum(taskID);
                userService.getTaskFee4Account(taskID,userAccount);
                return ResultVOUtil.success("任务审核通过");
            }
            else{
                return ResultVOUtil.error(202,"任务完成人数已满");
            }
        }
        else
        {
            taskMapper.taskFlag(taskID,userAccount,taskFlag);
            taskMapper.addUnfinishedTaskNum(taskID);
            return ResultVOUtil.error(404,"任务审核不通过");
        }

    }

    @GetMapping("/reportTask")
    public ResultVO reportTask(String taskID,String userAccount)  {
        if (StringUtils.isEmpty(taskID) || StringUtils.isEmpty(userAccount)) {
            return ResultVOUtil.error(404,"任务ID或用户账号为空");
        }
        TaskMaster repoTaskMaster = taskMapper.selectRepoTaskById(taskID,userAccount);
        if(repoTaskMaster!=null){
            return ResultVOUtil.error(404,"你已经举报过此任务");
        }
        else{
            TaskMaster taskMaster = taskMapper.selectTaskById(taskID);
            taskMapper.addToBlackList(taskMaster,userAccount);
            taskMapper.autoUpdate(taskID, TaskStatusEnum.REPORTED_AUDITING.getCode(),TaskStatusEnum.AUDITED.getCode());
            return ResultVOUtil.success("举报成功");
        }
    }



    /**
     * 功能描述: 接单排行徬
     * @Return:
     * @Author: jinLong
     * @Date: 2020/10/9 17:03
     */
    @GetMapping("/rankingListOrders")
    public ResultVO rankingListOrders(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String month = df.format(new Date()).substring(5, 7);
        return ResultVOUtil.success(taskMapper.rankingListOrders(month));
    }

    /**
     * 功能描述: 推广排行徬
     * @Return:
     * @Author: jinLong
     * @Date: 2020/10/13 15:21
     */
    @GetMapping("/rankingListSpread")
    public ResultVO rankingListSpread(){
        return ResultVOUtil.success(taskMapper.rankingListSpread());
    }








}

